package com.csweimei.rentmanagementtreasure.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.RequiresApi;

import com.csweimei.rentmanagementtreasure.utils.permission.RxPermissionsUtils;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

import me.goldze.mvvmhabit.utils.ToastUtils;


public class ValidateUtils {


    public static int daysBetween(String startDate) {
        Time startTime = new Time();
        Time endTime = new Time();

        startTime.parse3339(startDate);
        endTime.parse3339(getCurDate());

        return (int) ((endTime.toMillis(true) - startTime.toMillis(true)) / (1000 * 60 * 60 * 24));
    }


    public static String getCurDate(){
        // 获取当前时间戳（以毫秒为单位）
        long currentTimeMillis = System.currentTimeMillis();

// 创建一个Date对象，表示当前时间
        Date currentDate = new Date(currentTimeMillis);

// 创建一个SimpleDateFormat对象，用于格式化日期和时间
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

// 将Date对象格式化为字符串
        String formattedDate = dateFormat.format(currentDate);

        return formattedDate;
    }


    /**
     * 打电话
     * @param activity
     * @param phone
     */
    public static void callPhone(Activity activity,String phone){
        RxPermissionsUtils.phone(activity, new RxPermissionsUtils.Accept() {
            @Override
            public void accept() {
                Uri number = Uri.parse("tel:" + phone);
                Intent dial = new Intent(Intent.ACTION_DIAL);
                dial.setData(number);
                activity.startActivity(dial);
            }
        });

    }

    /**
     * 发短信
     * @param activity
     * @param phone
     */
    public static void msnPhone(Activity activity,String phone){
        String action = Intent.ACTION_SENDTO;
        String sms_body = "";
        Uri uri = Uri.parse("smsto:" + phone);
        Intent intent = new Intent(action, uri);
        intent.putExtra("sms_body", sms_body);
        activity.startActivity(intent);

    }

    public static String getTimeForm(String time){

        String originalString = time.replace("T"," ");
        char charToRemove = '.';
        int index = originalString.indexOf(charToRemove);

        // 如果找到了字符，则删除它后面的所有内容
        if (index != -1) {
            String newString = originalString.substring(0, index);
            return newString;
        } else {
            return originalString;
        }
    }


    public static String getTimeFormYMD(String time){
        if (time.contains("T")){
            String[] originalString = time.split("T");
            return originalString[0];
        }else {
            return time;
        }
    }

    public static String getTimeHm(String dateTimeStr){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        try {
            Date date = sdf.parse(dateTimeStr);
            System.out.println(date);

            SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm");

            String formattedDate = sdf1.format(date);

            return formattedDate;

        } catch (ParseException e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String TIME_YMD1 = "yyyy年MM月dd日 HH:mm";
    public static String TIME_YMD = "yyyy-MM-dd";
    public static String TIME_HM = "HH:mm";
    public static String TIME_YMDHMS = "yyyy-MM-dd HH:mm:ss";
    public static String TIME_YMDHM = "yyyy-MM-dd HH:mm";

    public static String getTimeByType(String dateTimeStr,String timeType){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        try {
            Date date = sdf.parse(dateTimeStr);
            System.out.println(date);

            SimpleDateFormat sdf1 = new SimpleDateFormat(timeType);

            String formattedDate = sdf1.format(date);

            return formattedDate;

        } catch (ParseException e) {
            e.printStackTrace();
            return "";
        }
    }



    /**
     * 检测手机号码
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {
        if (isNotEmptyObjectOrString(mobiles)) {
            String telRegex = "^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(147,145))\\d{8}$";
            return  mobiles.matches(telRegex);
        } else {
            return false;
        }
    }

    /**
     * 校验是否为空字符串
     *
     * @param validateStr 待校验的字符串
     * @return boolean
     */
    public static boolean isEmptyString(String validateStr) {
        return null == validateStr || StringUtils.STR_EMPTY.equals(validateStr)
                || StringUtils.STR_NULL_EN.equals(validateStr) || validateStr.length() == 0;
    }

    /**
     * 校验是否不为空字符串
     *
     * @param validateStr 待校验的字符串
     * @return boolean
     */
    public static boolean isNotEmptyString(String validateStr) {
        return !isEmptyString(validateStr);
    }

    /**
     * 校验是否为空json对象
     *
     * @param jo 待校验的json对象
     */
    public static boolean isEmptyOrgJsonObj(JSONObject jo) {
        return null == jo || jo.equals("[]") || StringUtils.STR_EMPTY.equals(jo);
    }

    /**
     * 校验是否不为空json对象
     *
     * @param jo 待校验的json对象
     */
    public static boolean isNotEmptyOrgJsonObj(JSONObject jo) {
        return !isEmptyOrgJsonObj(jo);
    }

    /**
     * 校验: 为空对象或者空字符串
     *
     * @param validateObj 待校验的对象
     * @return boolean
     */
    public static boolean isEmptyObjectOrString(Object validateObj) {
        return null == validateObj || StringUtils.STR_EMPTY.equals(validateObj.toString().trim());
    }

    /**
     * 校验: 不为为空对象或者空字符串
     *
     * @param validateObj 待校验的对象
     * @return boolean
     */
    public static boolean isNotEmptyObjectOrString(Object validateObj) {
        return !isEmptyObjectOrString(validateObj);
    }

    /**
     * 校验是否为空collection
     *
     * @param validateColl 待校验的collection
     * @return boolean
     */
    public static boolean isEmptyCollection(Collection<?> validateColl) {
        return null == validateColl || validateColl.size() == 0;
    }

    /**
     * 校验是否不为空collection
     *
     * @param validateColl 待校验的collection
     * @return boolean
     */
    public static boolean isNotEmptyCollection(Collection<?> validateColl) {
        return !isEmptyCollection(validateColl);
    }

    /**
     * 校验：为空Map
     *
     * @param validateMap 待校验的Map
     * @return boolean
     */
    public static boolean isEmptyMap(Map<?, ?> validateMap) {
        return null == validateMap || 0 == validateMap.entrySet().size() || validateMap.size() == 0;
    }

    /**
     * 校验: 不为空Map
     *
     * @param validateMap 待校验的Map
     * @return boolean
     */
    public static boolean isNotEmptyMap(Map<?, ?> validateMap) {
        return !isEmptyMap(validateMap);
    }


    /**
     * 判断网络连接是否可用
     *
     * @param context
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {
        boolean result = false;
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            // 如果仅仅是用来判断网络连接
            NetworkInfo[] info = cm.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        result = true;
                        break;
                    }
                }
            }
        }

        return result;
    }


    private static long lastClickTime;

    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        // 两次点击间隔小于500毫秒
        if (time - lastClickTime < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * @param times
     * @return
     * @方法说明:防止控件被重复点击，如果点击间隔时间小于指定时间就点击无 * @方法名称:isFastDoubleClick
     * @返回 boolean
     */
    public static boolean isFastDoubleClick(long times) {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < times) {
            return true;
        }
        lastClickTime = time;
        return false;
    }


    /**
     * 检测是否不为空字符串
     *
     * @param object
     * @return
     */
    public static String isCheck(String object) {
        if (isNotEmptyString(object)) {
            return object;
        } else {
            return "";
        }
    }

    public static String isCheck_1(String object) {
        if (isNotEmptyString(object)) {
            return object;
        } else {
            return "-1";
        }
    }

    /**
     * 检测是否不为空字符串
     *
     * @param s
     * @return
     */
    public static String isCheckInt(String s) {
        if (isNotEmptyString(s)) {
            return s;
        } else {
            return "0";
        }
    }

    /**
     * 没有选择数据
     *
     * @param s
     * @return
     */
    public static String noSelect(String s) {
        if (isNotEmptyString(s) && !"请选择".equals(isCheck(s))) {
            return s;
        } else {
            return "";
        }
    }

    public static String numToString(String s, String type) {
        if (isEmptyString(s)) {
            return "";
        }
        if ("Binddocumentis".equals(type)) {

            if ("1".equals(s)) {
                s = "已购买";
            } else {
                s = "未购买";
            }

        } else if ("Bindsumis".equals(type)) {

            if ("1".equals(s)) {
                s = "已缴纳";
            } else {
                s = "未缴纳";
            }

        } else if ("Businessbind".equals(type)) {
            if ("1".equals(s)) {
                s = "已完成";
            } else {
                s = "准备中";
            }


        } else if ("Technologybindis".equals(type)) {
            if ("1".equals(s)) {
                s = "已完成";
            } else {
                s = "准备中";
            }

        } else if ("Authorizationis".equals(type)) {
            if ("1".equals(s)) {
                s = "已完成";
            } else {
                s = "准备中";
            }
        }
        return s;
    }


    public static String typeid = ""; // 支出类别选中项 ID
    public static String typeName = ""; // 支出类别选中项 Name

    public static String projectid = ""; // 选择项目选中ID
    public static String projectName = ""; // 选择项目选中名称

    /**
     * 获取json
     *
     * @param names
     * @param strs
     * @return
     */
    public static String getJson(String[] names, String[] strs) {
        StringBuilder result = new StringBuilder("{\"");
        for (int i = 0; i < strs.length; i++) {
            result = result.append(names[i] + "\"");
            result = result.append(":\"");
            result = result.append(strs[i] + "\"");
            if (i < strs.length - 1)
                result = result.append(",\"");
        }
        result = result.append("}");

        return result.toString();
    }


    /**
     *  截取viewGroup长图(viewGroup整个内容区域大小)
     * 并保存到本地相册 通知相册更新
     * 在setContentView（）前判断
     * if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
     *       WebView.enableSlowWholeDocumentDraw();
     *  }
     * @param viewGroup 需要截取内容的容器
     * @param fileName 保存到本地的文件命名
     * @return 保存图片文件路径
     */
    public static String captureWebView(Context context, ViewGroup viewGroup) {
        String filePath="";
        //重新调用WebView的measure方法测量实际View的大小（将测量模式设置为UNSPECIFIED模式也就是需要多大就可以获得多大的空间）
        viewGroup.measure(View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        //调用layout方法设置布局（使用新测量的大小）
        viewGroup.layout(0, 0, viewGroup.getMeasuredWidth(), viewGroup.getMeasuredHeight());
        //开启WebView的缓存(当开启这个开关后下次调用getDrawingCache()方法的时候会把view绘制到一个bitmap上)
        viewGroup.setDrawingCacheEnabled(true);
        //强制绘制缓存（必须在setDrawingCacheEnabled(true)之后才能调用，否者需要手动调用destroyDrawingCache()清楚缓存）
        viewGroup.buildDrawingCache();
        //根据测量结果创建一个大小一样的bitmap
        Bitmap picture = Bitmap.createBitmap(viewGroup.getMeasuredWidth(),
                viewGroup.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
        //已picture为背景创建一个画布
        Canvas canvas = new Canvas(picture); // 画布的宽高和 WebView 的网页保持一致
        Paint paint = new Paint();
        //设置画笔的定点位置，也就是左上角
        canvas.drawBitmap(picture, 0, viewGroup.getMeasuredHeight(), paint);
        //将webview绘制在刚才创建的画板上
        viewGroup.draw(canvas);
        if (null != picture) {
            filePath= saveImageToGallery(context, picture,false);
        } else {
            ToastUtils.showShort("出错啦!");
        }
        return filePath;
    }

    /**
     * 保存Bitmap格式图片到系统文件夹
     * 并提醒系统图库更新
     * @param context
     * @param bmp
     * @param fileName 图片文件名 用以提醒系统图库更新
     * @return  filePath 图片文件的完整路径
     *
     */
    private static String saveImageToGallery(Context context, Bitmap bmp, boolean isNotify) {
        // 首先保存图片
        File appDir = new File("ZGB/shareImages");
        if (!appDir.exists()){
            appDir.mkdir();
            Log.e("TAG", "saveImageToGallery:文件夹不存在 "+appDir.getPath() );
            return "";
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir,fileName);
        if (!file.exists()){
            ToastUtils.showShort("文件不存在");
            Log.e("TAG", "saveImageToGallery:文件不存在 "+file.getPath() );
            try {
                file.createNewFile();
            } catch (IOException e) {
//                Log.e("123456", "saveImageToGallery:0 "+e.toString() );
                e.printStackTrace();
            }
            return "";
        }
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            Log.e("TAG", "saveImageToGallery1: "+e.toString() );
            e.printStackTrace();
        } catch (IOException e) {
            Log.e("TAG", "saveImageToGallery2: "+e.toString() );
            e.printStackTrace();
        }
        // 最后通知图库更新
        if (isNotify){
            // 其次把文件插入到系统图库
            try {
                MediaStore.Images.Media.insertImage(context.getContentResolver(),
                        file.getAbsolutePath(), fileName, null);
            } catch (FileNotFoundException e) {
                Log.e("TAG", "saveImageToGallery3: "+e.toString() );
                e.printStackTrace();
                return "";
            }
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fileName)));
        }
        return file.getPath();
    }


}
